package myadmin.jtthink.com.MyHelper;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.core.MethodParameter;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.annotation.RequestParamMapMethodArgumentResolver;
import org.springframework.web.method.annotation.RequestParamMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodArgumentResolverComposite;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@Component
public class ServiceParam {

    @Autowired
    ApplicationContext context;
    @Autowired
    ObjectMapper objectMapper;
    //用来解析参数 工具类
    private  HandlerMethodArgumentResolverComposite handlerMethodArgs;
    public ServiceParam(){
        List<HandlerMethodArgumentResolver> resolvers = new ArrayList<>();
        List<HttpMessageConverter<?>> messageConverters=new ArrayList<>();
        messageConverters.add(new StringHttpMessageConverter());
        messageConverters.add(new ByteArrayHttpMessageConverter());
        messageConverters.add(new MappingJackson2HttpMessageConverter());//json
        resolvers.add(new RequestResponseBodyMethodProcessor(messageConverters));
        resolvers.add(new RequestParamMapMethodArgumentResolver());
        DefaultListableBeanFactory defaultListableBeanFactory=new DefaultListableBeanFactory(this.context);
        resolvers.add(new RequestParamMethodArgumentResolver(defaultListableBeanFactory,false ));
        this.handlerMethodArgs=new HandlerMethodArgumentResolverComposite().addResolvers(resolvers);
    }


    public Object parseParam(Method method,int index, ServletWebRequest servletWebRequest) throws Exception {
        MethodParameter methodParameter=new MethodParameter(method,index);

        return this.handlerMethodArgs.resolveArgument(methodParameter,
                null,servletWebRequest,null);
    }
 }
